package com.ruoyi.robot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.robot.pojo.po.Customer;
import com.ruoyi.robot.mapper.CustomerMapper;
import com.ruoyi.robot.pojo.dto.CustomerDto;
import com.ruoyi.robot.pojo.dto.LoginDto;
import com.ruoyi.robot.service.CustomerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.robot.util.DtoToPoMapper;
import com.ruoyi.robot.util.JWTUtils;
import com.ruoyi.robot.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xds
 * @since 2023-01-16
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    private final CustomerMapper customerMapper;
    private final RedisCache redisCache;

    @Autowired
    public CustomerServiceImpl(RedisCache redisCache,CustomerMapper customerMapper){
        this.redisCache = redisCache;
        this.customerMapper = customerMapper;
    }


    /**
     * 查询用户表
     *
     * @param customerId 用户表主键
     * @return 用户表
     */
    @Override
    public Customer selectCustomerByCustomerId(Long customerId)
    {
        return customerMapper.selectById(customerId);
    }


    /**
     * 查询用户表列表
     *
     * @param customerDto 用户表
     * @return 用户表
     */
    @Override
    public List<Customer> selectCustomerList(CustomerDto customerDto)
    {
        Customer customer = DtoToPoMapper.INSTANCE.toCustomer(customerDto);
        return customerMapper.selectCustomerList(customer);
    }


    /**
     * 新增用户表
     *
     * @param customerDto 用户表
     * @return 结果
     */
    @Override
    public AjaxResult insertCustomer(CustomerDto customerDto)
    {
        Customer customer = DtoToPoMapper.INSTANCE.toCustomer(customerDto);
        QueryWrapper<Customer>wrapper = new QueryWrapper<>();
        wrapper.eq("customer_account",customer.getCustomerAccount());
        if(customerMapper.selectCount(wrapper) != 0){
            return AjaxResult.error("该账户已经存在");
        }

        String passWord = customerDto.getCustomerPassword();
        customer.setCustomerPassword(SecurityUtils.encryptPassword(passWord));
        return customerMapper.insert(customer) > 0?AjaxResult.success("注册成功"):AjaxResult.error("注册失败");
    }


    /**
     * 修改用户表
     *
     * @param customerDto 用户表
     * @return 结果
     */
    @Override
    public int updateCustomer(CustomerDto customerDto)
    {
        Customer customer = DtoToPoMapper.INSTANCE.toCustomer(customerDto);
        return customerMapper.updateById(customer);
    }


    /**
     * 批量删除用户表
     *
     * @param customerIds 需要删除的用户表主键
     * @return 结果
     */
    @Override
    public int deleteCustomerByCustomerIds(Long[] customerIds)
    {
        return customerMapper.deleteCustomerByCustomerIds(customerIds);
    }


    /**
     * 删除用户表信息
     *
     * @param customerId 用户表主键
     * @return 结果
     */
    @Override
    public int deleteCustomerByCustomerId(Long customerId)
    {
        return customerMapper.deleteById(customerId);
    }

    @Override
    public AjaxResult login(LoginDto loginDto) {
        QueryWrapper<Customer>wrapper = new QueryWrapper<>();
        wrapper.eq("customer_account",loginDto.getCustomerAccount());
        Customer customer = customerMapper.selectOne(wrapper);
        String code = redisCache.getCacheObject(loginDto.getVertifyKey());
        redisCache.deleteObject(loginDto.getVertifyKey());
//        if(!loginDto.getCode().equals(code)){
//            return AjaxResult.error("验证码错误");
//        }

        if(customer == null){
            return AjaxResult.error("该用户不存在");
        }

        if(!SecurityUtils.matchesPassword(loginDto.getCustomerPassword(),customer.getCustomerPassword())){
            return AjaxResult.error("密码错误");
        }


        String token = JWTUtils.getToken(customer);
        return AjaxResult.success(token);

    }

    @Override
    public AjaxResult generateImageCode(HttpServletResponse response) throws IOException {
        // 使用工具类生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //  将验证码存入redis，对应UUID作为key
        String UUIDKey = UUID.randomUUID().toString();
        redisCache.setCacheObject(UUIDKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //将得到的验证码，使用工具类生成验证码图片，并放入到字节数组缓存区
        VerifyCodeUtils.outputImage(220, 60, byteArrayOutputStream, code);
        //使用spring提供的工具类，将字节缓存数组中的验证码图片流转换成Base64的形式
        //并返回给浏览器
        AjaxResult AjaxResult = new AjaxResult();
        AjaxResult.put("VerifyCode","data:image/png;base64," + Base64Utils.encodeToString(byteArrayOutputStream.toByteArray()));
        AjaxResult.put("UUIDKey",UUIDKey);
        return AjaxResult.success(AjaxResult);
    }
}
